﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TravelLink.Common;
using TravelLink.DAL;

namespace TravelLink.ScheduleTasks.Service {
    public class MailSvc : IMailSvc {

        #region IMailSvc 成员

        public void Test() {
            LogWriter.Info("Test Msg");
        }

        public void SendPostionInfo(Guid userCode) {
            try {
                using (TravelLinkDBDataContext db = DataContextFactory.Create()) {
                    //用户查询
                    var userQuery = from u in db.TL_User
                                    from v in db.TL_User_Subscription
                                    where u.UserCode == v.UserCode && u.UserCode == userCode
                                    select new UserInfo {
                                        UserCode = u.UserCode,
                                        Name = u.CFirstName + u.CLastName,
                                        Email = u.Email,
                                        IndustryType = v.IndustryType,
                                        PositionType = v.PositionType,
                                        Period = v.Period ?? 0,
                                        City = v.City,
                                        Level = v.PositionLevel,
                                        FirstName = u.CFirstName,
                                        LastName = u.CLastName
                                    };

                    var users = userQuery.ToList();
                    if (users.Count <= 0) return;
                    var sendUser = users.First();
                    int addDays = -7;
                    switch (sendUser.Period) {
                        case 0: addDays = -999; break;
                        case 1: addDays = -7; break;
                        case 2: addDays = -14; break;
                        case 3: addDays = -30; break;
                        case 4: addDays = -60; break;
                        case 5: addDays = -90; break;
                        default: addDays = -180; break;
                    }



                    //职位查询
                    var postionQuery = from p in db.TL_Company_Position
                                       from c in db.TL_Company
                                       where p.CompanyCode == c.CompanyCode
                                       && p.PublishDate >= DateTime.Now.AddDays(addDays).Date
                                       //  && p.PeriodTo >= DateTime.Now.Date
                                       from a in db.TL_City
                                       where p.WorkInCityId == a.Idx
                                       select new
                                       {
                                           CompanyCode = c.CompanyCode,
                                           CommpanyName = c.CompanyName,
                                           PositionName = p.PositionName,
                                           PositionDescription = p.Description,
                                           Area = a.CName,
                                           PositionId = p.PositionCode,
                                           p.PositionType,
                                           p.WorkInCityId,
                                           p.PositionLevel
                                       };
                    var positions = postionQuery.ToList();
                    foreach (var user in users) {
                        if (!string.IsNullOrEmpty(user.Email)) {
                            try {
                                List<Guid> companyCodes = new List<Guid>(0);
                                if (!string.IsNullOrEmpty(user.IndustryType)) {
                                    List<int> industryTypeIDs = user.IndustryType.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(u => int.Parse(u)).ToList();

                                    if (industryTypeIDs.Count > 0 && industryTypeIDs.IndexOf(-1) < 0) {
                                        companyCodes = db.TL_Company_Industry.Where(u => industryTypeIDs.Contains(u.IndustryId)).Select(u => u.CompanyCode).Distinct().ToList();
                                    }
                                }
                                var userPostions = companyCodes.Count > 0 ? positions.Where(u => companyCodes.Contains(u.CompanyCode)).ToList() : positions.ToList();

                                if (!string.IsNullOrEmpty(user.PositionType)) {
                                    List<int> positionIds = user.PositionType.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(u => int.Parse(u)).ToList();

                                    if (positionIds.Count > 0 && positionIds.IndexOf(-1) < 0) {
                                        userPostions = userPostions.Where(u => positionIds.Contains((u.PositionType ?? 0))).ToList();
                                    }
                                }
                                if (!string.IsNullOrEmpty(user.Level)) {
                                    List<int> levelIds = user.Level.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(u => int.Parse(u)).ToList();

                                    if (levelIds.Count > 0 && levelIds.IndexOf(-1) < 0) {
                                        userPostions = userPostions.Where(u => levelIds.Contains((u.PositionLevel ?? 0))).ToList();
                                    }
                                }

                                if (!string.IsNullOrEmpty(user.City)) {
                                    List<int> citys = user.City.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(u => int.Parse(u)).ToList();

                                    if (citys.Count > 0 && citys.IndexOf(-1) < 0) {
                                        userPostions = userPostions.Where(u => citys.Contains((u.WorkInCityId ?? 0))).ToList();
                                    }
                                }
                                if (userPostions.Count > 0) {
                                    var sendPostionList = userPostions.Take(5)
                                        .Select(u => string.Format(@"
   <div id='job_news_zp'>
                <div id='job_news_zp_titel'>
                    {0}</div>
                <div id='job_news_zp_recr'>
                    {1} | 旅行社 | {2}</div>
                <div id='job_news_zp_view'>
                    <a href='{3}'>
                        <img src='http://www.travellinkrecruitment.com/images/job_pic_20.jpg' width='69'
                            height='12' border='0' /></a></div>
                <div id='job_news_zp_ine'>
                    <img src='http://www.travellinkrecruitment.com/images/job_pic_19.jpg' /></div>
            </div>", u.CommpanyName, u.PositionName, u.Area, string.Concat(Utility.SiteRoot, TravelLink.WebModel.Consts.PositionDetail(u.PositionId)))).ToList();
                                    MailSender.SendMailByRecommendByAuto(string.Concat(user.FirstName, user.LastName), sendPostionList, user.Email);
                                }

                            }
                            catch (Exception ex) {
                                LogWriter.Info(ex.Message);
                                continue;
                            }
                        }
                    }
                }

            }
            catch (Exception ex) {
                LogWriter.Error("MailSvc->SendPositionInfo", ex);
            }
        }


        public void SendPositionInfo() {
            try {
                using (TravelLinkDBDataContext db = DataContextFactory.Create()) {
                    //用户查询
                    var userQuery = from u in db.TL_User
                                    from v in db.TL_User_Subscription
                                    where u.UserCode == v.UserCode
                                    select new UserInfo {
                                        UserCode = u.UserCode,
                                        Name = u.CFirstName + u.CLastName,
                                        Email = u.Email,
                                        IndustryType = v.IndustryType,
                                        PositionType = v.PositionType
                                    };

                    var users = userQuery.ToList();
                    //职位查询
                    var postionQuery = from p in db.TL_Company_Position
                                       from c in db.TL_Company
                                       where p.CompanyCode == c.CompanyCode && p.PublishDate >= DateTime.Now.AddDays(-7).Date && p.PeriodTo >= DateTime.Now.Date
                                       from a in db.TL_City
                                       where p.WorkInCityId == a.Idx
                                       select new
                                       {
                                           CompanyCode = c.CompanyCode,
                                           CommpanyName = c.CompanyName,
                                           PositionName = p.PositionName,
                                           PositionDescription = p.Description,
                                           Area = a.CName,
                                           PositionId = p.PositionCode,
                                       };
                    var positions = postionQuery.ToList();
                    foreach (var user in users) {
                        if (!string.IsNullOrEmpty(user.IndustryType) && !string.IsNullOrEmpty(user.Email)) {
                            try {
                                List<int> industryTypeIDs = user.IndustryType.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(u => int.Parse(u)).ToList();
                                List<Guid> companyCodes;
                                if (industryTypeIDs.IndexOf(-1) >= 0) {
                                    companyCodes = db.TL_Company_Industry.Select(u => u.CompanyCode).Distinct().ToList();
                                }
                                else {
                                    companyCodes = db.TL_Company_Industry.Where(u => industryTypeIDs.Contains(u.IndustryId)).Select(u => u.CompanyCode).Distinct().ToList();
                                }
                                var userPostions = positions.Where(u => companyCodes.Contains(u.CompanyCode)).ToList();

                                if (userPostions.Count > 0) {
                                    var sendPostionList = userPostions.Take(5)
                                        .Select(u => string.Format(@"
   <div id='job_news_zp'>
                <div id='job_news_zp_titel'>
                    {0}</div>
                <div id='job_news_zp_recr'>
                    {1} | 旅行社 | {2}</div>
                <div id='job_news_zp_view'>
                    <a href='{3}'>
                        <img src='http://www.travellinkrecruitment.com/images/job_pic_20.jpg' width='69'
                            height='12' border='0' /></a></div>
                <div id='job_news_zp_ine'>
                    <img src='http://www.travellinkrecruitment.com/images/job_pic_19.jpg' /></div>
            </div>", u.CommpanyName, u.PositionName, u.Area, string.Concat(Utility.SiteRoot, TravelLink.WebModel.Consts.PositionDetail(u.PositionId)))).ToList();
                                    MailSender.SendMailByRecommendByAuto(string.Concat(user.FirstName, user.LastName), sendPostionList, user.Email);
                                }

                            }
                            catch (Exception ex) {
                                LogWriter.Info(ex.Message);
                                continue;
                            }
                        }
                    }
                }

            }
            catch (Exception ex) {
                LogWriter.Error("MailSvc->SendPositionInfo", ex);
            }
        }

        #endregion






    }

    public class UserInfo {

        public Guid UserCode { get; set; }

        public string Name { get; set; }

        public string Email { get; set; }

        public string PositionType { get; set; }

        public string IndustryType { get; set; }

        public int Period { get; set; }

        public string City { get; set; }

        public string Level { get; set; }

        public string FirstName { get; set; }

        public string LastName { get; set; }
    }
}
